﻿using System;
using System.Data.Services.Client;
using System.Linq;
using System.Windows.Input;
using BusinessObjects;
using LogInModule.Models;
using Microsoft.Practices.Composite.Presentation.Commands;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Unity;
using YourWorld.Common;
using YourWorld.Common.GreenWorldEntitiesService;
using YourWorld.Common.Infrastucture.Events;
using MainGameModule.Models;

namespace LogInModule.ViewModels
{

    public class UserLogInViewModel : ViewModelBase
    {
        private ILoginModel model;
        private IRegionManager regionManager;
        private IUnityContainer container;

        public event Action OnSuccessfulLogIn;

        private bool isBusy = false;
        private string email;
        private string password;
        private string username;
        private string repeatPassword;
        private string errorMessage;
        private string nickname;

        public ICommand GuestPlayCommand
        {
            get;
            private set;
        }

        public ICommand LoginCommand
        {
            get;
            set;
        }

        public ICommand RegisterCommand
        {
            get;
            set;
        }

        public ICommand UpdateCommand
        {
            get;
            set;
        }

        public string Email
        {
            get { return this.email; }
            set
            {
                if ( this.email != value )
                {
                    this.email = value;
                    this.NotifyPropertyChanged( "Email" );
                }
            }
        }

        public string Password
        {
            get { return this.password; }
            set
            {
                if ( this.password != value )
                {
                    this.password = value;
                    this.NotifyPropertyChanged( "Password" );
                }
            }
        }

        public string Username
        {
            get { return this.username; }
            set
            {
                if ( this.username != value )
                {
                    this.username = value;
                    this.NotifyPropertyChanged( "Username" );
                }
            }
        }

        public string RepeatPassword
        {
            get { return this.repeatPassword; }
            set
            {
                if ( this.repeatPassword != value )
                {
                    this.repeatPassword = value;
                    this.NotifyPropertyChanged( "RepeatPassword" );
                }
            }
        }

        public string ErrorMessage
        {
            get { return this.errorMessage; }
            set
            {
                if ( this.errorMessage != value )
                {
                    this.errorMessage = value;
                    this.NotifyPropertyChanged( "ErrorMessage" );
                }
            }
        }

        public bool IsBusy
        {
            get { return this.isBusy; }
            set
            {
                if ( this.isBusy != value )
                {
                    this.isBusy = value;
                    this.NotifyPropertyChanged( "IsBusy" );
                }
            }
        }

        public string Nickname
        {
            get
            {
                return this.nickname;
            }
            set
            {
                if ( this.nickname != value )
                {
                    this.nickname = value;
                    this.NotifyPropertyChanged( "Nickname" );
                }
            }
        }


        public UserLogInViewModel( ILoginModel model, IRegionManager regionManager, IUnityContainer container )
        {
            this.model = model;
            this.regionManager = regionManager;
            this.container = container;

            this.LoginCommand = new DelegateCommand<string>( this.OnLogIn );
            this.RegisterCommand = new DelegateCommand<string>( this.OnRegister );
            this.UpdateCommand = new DelegateCommand<string>( this.OnUpdate );
            this.GuestPlayCommand = new DelegateCommand<object>( this.PlayAsGuest );

            this.model.LoginSuccessful += this.LoginSucceeded;
            this.model.WrongCredentialsEvent += this.WrongCredentials;
        }

        public void PlayAsGuest( object param )
        {
            Player player = new Player()
            {
                Name = this.Nickname,
                IsGuest = true,
                IsMainPlayer = true
            };

            EventService.Aggregator.GetEvent<PlayerLoginSuccessfulEvent>().Publish( player );

            // inform the view to proceed to game mode selection
            if ( this.OnSuccessfulLogIn != null )
                this.OnSuccessfulLogIn();
        }

        public void CleanForm()
        {
            this.Email = string.Empty;
            this.Password = string.Empty;
            this.Username = string.Empty;
            this.RepeatPassword = string.Empty;
            this.ErrorMessage = string.Empty;
        }

        public bool InitializeProfileInformation()
        {
            if ( string.IsNullOrEmpty( this.Email ) || string.IsNullOrEmpty( this.Password ) )
            {
                this.ErrorMessage = "Empty field.";
                return false;
            }
            //return true;
            // TODO - register new
            //YourWorld.Common.GreenWorldEntitiesService.User user = this.users.Where(u => u.Email == this.Email && u.Password == this.Password).FirstOrDefault();
            YourWorld.Common.GreenWorldEntitiesService.User user = PlayersRepository.Instance.Users.Where(u => u.Email == this.Email && u.Password == this.Password).FirstOrDefault();
            if (user == null)
            {
                this.ErrorMessage = "Please provide valid email and password.";
                return false;
            }
            else
            {
                this.Username = user.Name;
                this.RepeatPassword = this.Password;
                this.ErrorMessage = string.Empty;
                return true;
            }
        }

        private void LoginSucceeded( Player player )
        {
            this.IsBusy = false;

            EventService.Aggregator.GetEvent<PlayerLoginSuccessfulEvent>().Publish( player );

            // inform the view to proceed to game mode selection
            if ( this.OnSuccessfulLogIn != null )
                this.OnSuccessfulLogIn();
        }

        private void WrongCredentials()
        {
            this.IsBusy = false;
            this.ErrorMessage = "Invalid email or password.";
        }

        private void OnUpdate( string notUsed )
        {
            if (string.IsNullOrEmpty(this.Password) || string.IsNullOrEmpty(this.Username) || string.IsNullOrEmpty(this.RepeatPassword))
            {
                this.ErrorMessage = "Empty field.";
                return;
            }

            if (string.Compare(this.Password, this.RepeatPassword) != 0)
            {
                this.ErrorMessage = "Passwords don't match.";
                return;
            }

            //this.model.UpdateUser(this.Email, this.Username, this.Password);

            //this.IsBusy = true;
            //YourWorld.Common.GreenWorldEntitiesService.User editedUser = 
            //    PlayersRepository.Instance.Users.Where(u => u.Email == this.Email).FirstOrDefault();
            //if (editedUser != null)
            //{
            //    editedUser.Name = string.Copy(this.Username);
            //    editedUser.Password = string.Copy(this.Password);

            //    Player logInPlayer = new Player()
            //    {
            //        Id = editedUser.Id,
            //        Image = editedUser.PicUrl,
            //        Name = editedUser.Name,
            //        Badges = editedUser.Badges,
            //        Quests = editedUser.Quests,
            //        IsMainPlayer = true
            //    };

            //    // inform the model
            //    this.model.SaveUsers(logInPlayer,
            //        (result) =>
            //        {
            //            // inform the view to proceed to game mode selection when the new user is saved
            //            if (this.OnSuccessfulLogIn != null)
            //            {
            //                this.IsBusy = false;
            //                this.CleanForm();
            //                this.OnSuccessfulLogIn();
            //            }
            //        });
            //}
        }

        private void OnLogIn( string notUsed )
        {
            if ( string.IsNullOrEmpty( this.Email ) || string.IsNullOrEmpty( this.Password ) )
            {
                this.ErrorMessage = "Empty field.";
                return;
            }

            this.IsBusy = true;
            this.model.LoadUser( this.Email, this.Password );

            //User loginUser = this.users.Where( u => u.Email == this.Email && u.Password == this.Password ).FirstOrDefault();

            //if ( loginUser == null )
            //{
            //    this.ErrorMessage = "Invalid email or password.";
            //    return;
            //}

            //Player logInPlayer = new Player()
            //{
            //    Id = loginUser.Id,
            //    Image = loginUser.PicUrl,
            //    Name = loginUser.Name,
            //    Badges = loginUser.Badges,
            //    Quests = loginUser.Quests,
            //    IsMainPlayer = true
            //};

            //// inform the model
            //this.model.Login( logInPlayer );
            //this.CleanForm();

            //// inform the view to proceed to game mode selection
            //if ( this.OnSuccessfulLogIn != null )
            //    this.OnSuccessfulLogIn();
        }

        private void OnRegister( string notUsed )
        {//TODO - check for existing user
            if (string.IsNullOrEmpty(this.Email) || string.IsNullOrEmpty(this.Password)
                || string.IsNullOrEmpty(this.Username) || string.IsNullOrEmpty(this.RepeatPassword))
            {
                this.ErrorMessage = "Empty field.";
                return;
            }

            //if (PlayersRepository.Instance.Users.Where(u => string.Compare(u.Email, this.Email) == 0).FirstOrDefault() != null)
            //{
            //    this.ErrorMessage = "There is already a user with this email.";
            //    return;
            //}

            if (string.Compare(this.Password, this.RepeatPassword) != 0)
            {
                this.ErrorMessage = "Passwords don't match.";
                return;
            }

            this.IsBusy = true;
            this.model.AddUser(this.Email, this.Username, this.Password);

            //YourWorld.Common.GreenWorldEntitiesService.User newUser = new YourWorld.Common.GreenWorldEntitiesService.User();
            //newUser.Email = string.Copy(this.Email);
            //newUser.Name = string.Copy(this.Username);
            //newUser.Password = string.Copy(this.Password);
            //PlayersRepository.Instance.Users.Add(newUser);

            //Player logInPlayer = new Player()
            //{
            //    Id = newUser.Id,
            //    Image = newUser.PicUrl,
            //    Name = newUser.Name,
            //};

            //// inform the model
            //this.model.SaveUsers(logInPlayer, (result) =>
            //{
            //    (this.model as LoginModel).GetUsersAsync(this.OnRegisterSucceeded);

            //});
        }

        private void OnRegisterSucceeded( DataServiceCollection<User> latestUsers )
        {
            YourWorld.Common.GreenWorldEntitiesService.User loginUser = PlayersRepository.Instance.Users.Where(u => u.Email == this.Email && u.Password == this.Password).FirstOrDefault();

            Player logInPlayer = new Player()
            {
                Id = loginUser.Id,
                Image = loginUser.PicUrl,
                Name = loginUser.Name,
                Badges = loginUser.Badges,
                Quests = loginUser.Quests,
                IsMainPlayer = true
            };

            // inform the model
            this.model.Login(logInPlayer);

            if (this.OnSuccessfulLogIn != null)
            {
                this.IsBusy = false;
                this.CleanForm();
                this.OnSuccessfulLogIn();
            }
        }

        private void LoadUsers()
        {
            // this.IsBusy = true;
            // this.model.UsersLoaded += new System.Action<DataServiceCollection<YourWorld.Common.GreenWorldEntitiesService.User>>( this.OnUsersLoaded );
            // this.model.GetUsersAsync();
        }

        private void OnUsersLoaded( DataServiceCollection<YourWorld.Common.GreenWorldEntitiesService.User> loadedUsers )
        {
            //  this.IsBusy = false;
        }
    }
}
